package com.travelingsalesmen.post.rmi;

import com.travelingsalesmen.post.Catalog;
import com.travelingsalesmen.post.Invoice;
import java.io.*;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server extends UnicastRemoteObject implements IServer, Serializable {

    private Catalog catalog;
    private List<Invoice> invoices = new ArrayList<Invoice>();
    private File logFile = new File("log.txt");

    public Server() throws RemoteException {
    }

    public void setCatalog(Catalog catalog) throws RemoteException {
        this.catalog = catalog;
    }

    public Catalog getCatalog() throws RemoteException {
        return catalog;
    }

    public void uploadInvoice(Invoice invoice) throws RemoteException {
        invoices.add(invoice);
    }

    public List<Invoice> getInvoices() throws RemoteException {
        return invoices;
    }

    public int getNumberOfSales() throws RemoteException {
        return invoices.size();
    }

    public void printInvoices() throws RemoteException {
        System.out.println("Printing invoices");
        for (Invoice invoice : invoices) {
            System.out.println(invoice);
        }
    }

    public void printInvoicesToFile() throws RemoteException {
        try {
            if (!logFile.exists()) {
                try {
                    logFile.createNewFile();
                } catch (IOException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            FileWriter fileWritter = new FileWriter(logFile.getName(), true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            for (Invoice in : invoices) {
                if (!in.isInFile()) {
                    bufferWritter.newLine();
                    bufferWritter.write(in.toString());
                    bufferWritter.newLine();
                    in.setInFile(true);
                }
            }
            bufferWritter.close();
        } catch (IOException e) {
        }
    }
}